﻿using System;
using System.Web.Compilation;
using System.Web.Configuration;

namespace visinia.SmartEngine.Providers
{
    /// <summary>
    /// ProviderController class controls dynamic loading and initialization of providers e.g.
    /// data providers etc.
    /// </summary>
    public class ProviderController
    {   
        /// <summary>
        /// Creates the data provider dynamically
        /// </summary>        
        /// <param name="ProviderNamespace">The provider namespace</param>
        /// <returns>The Provider object</returns>
        public static object CreateDataProvider(string ProviderNamespace)
        {
            DataProviderSection section = (DataProviderSection)WebConfigurationManager.GetWebApplicationSection("visinia/DataProvider");
            string type = ProviderNamespace + "." + section.DefaultDataProvider;
            Type Provider = BuildManager.GetType(type, false, true);
            return Activator.CreateInstance(Provider);
        }
                
        /// <summary>
        /// Gets the DataProvider connection string
        /// </summary>        
        public static string GetDataProviderConnectionString()
        {
            string connectionString = "";
            DataProviderSection section = (DataProviderSection)WebConfigurationManager.GetWebApplicationSection("visinia/DataProvider");
            try
            {
                connectionString = WebConfigurationManager.ConnectionStrings[section.DefaultDataProviderConnectionString].ConnectionString;
            }
            catch
            {
                if (string.IsNullOrEmpty(connectionString))
                    throw new Exception("DataProvider ConnectionString Not Found");
            }
            return connectionString;
        }
    }
}